import xlrd
import os

from common.log import Log
from conf.config import data_path
from common.config_parse import YamlConfig
from common.db_creator import DbCreator


class DataParse:
    def __init__(self, file_name):
        new_file_name = os.path.join(data_path, file_name)
        if not os.path.isfile(new_file_name):
            Log.error("参数化文件不存在！{}", new_file_name)
            raise FileNotFoundError
        self.new_file_name = new_file_name

    @property
    def form_txt(self, ): #txt,csv
        data_list = []
        index = 0
        with open(self.new_file_name, encoding="utf-8") as fr:
            for line in fr:#每行的数据是str
                line = line.strip()
                if line:
                    if index == 0:
                        # fields = line.split(',')
                        fields = line
                        index += 1
                    else:
                        data_list.append(line.split(','))
            # return ','.join(fields), data_list
            return fields, data_list

    @property
    def form_excel(self):#最近xlrd更新到了2.0.1版本，只支持.xls文件,pip install xlrd==1.2.0
        data_list = []
        book = xlrd.open_workbook(self.new_file_name)
        sheet = book.sheet_by_index(0)
        for row_number in range(sheet.nrows):
            row = sheet.row_values(row_number)#每行的数据是list
            if row_number == 0:
                fields = row
            else:
                data_list.append(row)
        return ','.join(fields), data_list
        # return fields, data_list
    # ('username,password', [['uhe@hotmail.com', 123456.0], ['1uhe@hotmail.com', 123456.0], ['1uhe@hotmail.com', 1234567.0], ['', 23456.0], ['uhe@hotmail.com', ''], [13140220163.0, 123456.0]])

    @property
    def form_yaml(self):
        data_list = []
        data = YamlConfig.get_config_form_yaml(self.new_file_name)
        fields = list(data[0].keys())
        for d in data:
            data_list.append(list(d.values()))
        return ','.join(fields), data_list

    @staticmethod
    def form_mysql(sql):
        data_list = []
        mysql_obj = DbCreator().mysql_creator(data_type=2) #[{},{}]
        data = mysql_obj.fetchall(sql)
        # print("data:%s"%data)
        # print("data[0]:%s"%data[0])
        fields = list(data[0].keys())
        for d in data:
            data_list.append(list(d.values()))
        return ','.join(fields), data_list


    def form_redis(self):
        pass

    def form_xx(self):
        pass


if __name__ == '__main__':
    # dp = DataParse("login.txt")
    # data_list = dp.form_txt
    # print(data_list)

    # dp = DataParse("login.xlsx")
    # data_list = dp.form_excel
    # print(data_list)

    # dp = DataParse("login.yaml")
    # data_list = dp.form_yaml
    # print(data_list)

    sql='select email as username,password from fmz_user limit 5'
    print(DataParse.form_mysql(sql))


